package com.ruoyi.framework.security.filter

import com.ruoyi.common.utils.MyStringUtils
import com.ruoyi.common.utils.SecurityUtils.authentication
import com.ruoyi.framework.web.service.TokenService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import java.io.IOException
import javax.servlet.FilterChain
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * token过滤器 验证token有效性
 *
 * @author ruoyi
 */
@Component
class JwtAuthenticationTokenFilter : OncePerRequestFilter() {
    @Autowired
    private lateinit var tokenService: TokenService
    @Throws(ServletException::class, IOException::class)
    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
        val loginUser = tokenService.getLoginUser(request)
        if (MyStringUtils.isNotNull(loginUser) && MyStringUtils.isNull(authentication)) {
            tokenService.verifyToken(loginUser)
            val authenticationToken = UsernamePasswordAuthenticationToken(loginUser, null, loginUser?.authorities)
            authenticationToken.details = WebAuthenticationDetailsSource().buildDetails(request)
            SecurityContextHolder.getContext().authentication = authenticationToken
        }
        chain.doFilter(request, response)
    }
}
